package com.karry.yl.web.baseinfo;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.karry.commons.PDFGenerator;
import com.karry.commons.base.SuperController;
import com.karry.commons.util.ObjectTransverter;
import com.karry.commons.util.TimeUtil;
import com.karry.commons.vo.JsonResponse;
import com.karry.commons.vo.LayTableResponse;
import com.karry.yl.domain.baseinfo.Employee;
import com.karry.yl.domain.baseinfo.EmployeeCertificate;
import com.karry.yl.domain.personnel.Department;
import com.karry.yl.domain.personnel.Post;
import com.karry.yl.domain.personnel.Train;
import com.karry.yl.domain.system.Role;
import com.karry.yl.domain.system.User;
import com.karry.yl.service.baseinfo.EmployeeCertificateService;
import com.karry.yl.service.baseinfo.EmployeeService;
import com.karry.yl.service.personnel.DepartmentService;
import com.karry.yl.service.personnel.PostService;
import com.karry.yl.service.personnel.TrainService;
import com.karry.yl.service.system.RoleService;
import com.karry.yl.service.system.UserService;
import com.karry.yl.web.elder.ElderlyController;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.ponly.fs.FileSystem;
import org.ponly.fs.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 楼宇信息Controller
 */
@Controller
@RequestMapping("/employee")
public class EmployeeController extends SuperController {

    private static final Logger LOG = LoggerFactory.getLogger(ElderlyController.class);
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private EmployeeCertificateService employeeCertificateService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PostService postService;
    @Autowired
    private FileSystem fs;
    @Autowired
    private TrainService trainService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    /**
     * 到从业人员列表页
     *
     * @return
     */
    @RequestMapping
    public String listUI() {
        return "baseinfo/employee/list";
    }

    /**
     * 跳转到证书上传的弹窗页
     *
     * @return
     */
    @RequestMapping("/uploadCertificate")
    public String uploadCertificate() {
        return "baseinfo/employee/certificateAdd";
    }

    /**
     * 跳转到证书上传的弹窗页
     *
     * @return
     */
    @RequestMapping("/uploadTrainAdd")
    public String uploadTrainAdd() {
        return "baseinfo/employee/trainAdd";
    }

    @RequestMapping("/add")
    public String addUI(Long id, ModelMap modelMap) {
        //部门
        Department department = departmentService.selectById(id);
        List<Post> posts = postService.selectList(new EntityWrapper<Post>().eq("orgId", currentUser.getOrgId()));
        modelMap.put("department", department);
        modelMap.put("posts", posts);
        return "baseinfo/employee/add";
    }

    @RequestMapping("/userAddUI")
    public String userAdd(Long id, ModelMap modelMap) {
        Employee employee = employeeService.selectById(id);
        modelMap.put("employee", employee);
        Long userId = employee.getUserId();
        //之前没有设置登陆信息
        User user = new User();
        if (userId != null && userId != -1) {
            user = userService.selectById(userId);
        }
        modelMap.put("user", user);
        List<Role> roles = roleService.selectList(new EntityWrapper<Role>().eq("orgId", currentUser.getOrgId()).eq("deleted", false));
        modelMap.put("roles", roles);
        return "baseinfo/employee/loginSetting";
    }

    @RequestMapping("/saveUser")
    @ResponseBody
    public JsonResponse saveUser(String data) {
        try {
            employeeService.saveUser(data, currentUser.getOrgId());
            return new JsonResponse(200, "成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResponse(0, "失败");
    }

    @RequestMapping("/edit")
    public String editUI(Long id, ModelMap map) {
        //部门
        List<Department> departments = departmentService.selectList(new EntityWrapper<Department>().eq("orgId", currentUser.getOrgId()));
        List<Post> posts = postService.selectList(new EntityWrapper<Post>().eq("orgId", currentUser.getOrgId()));
        map.put("departments", departments);
        map.put("posts", posts);
        Employee employee = employeeService.selectById(id);
        String laborContracts = employee.getLaborContract();
        List<String> laborContractArray = new ArrayList<>();
        if (!StringUtils.isEmpty(laborContracts)) {
            if (laborContracts.contains(",")) {
                laborContractArray.addAll(Arrays.asList(laborContracts.split(",")));
            } else {
                laborContractArray.add(laborContracts);
            }
        }
        map.put("laborContractArray", laborContractArray);
        map.put("employee", employee);
        List<EmployeeCertificate> certs = employeeCertificateService.selectList(new EntityWrapper<EmployeeCertificate>().eq("orgId", currentUser.getOrgId()).eq("employeeId", employee.getId()).eq("deleted", false));
        map.put("certs", certs);
        List<Train> trains = trainService.selectList(new EntityWrapper<Train>().eq("orgId", currentUser.getOrgId()).eq("employeeId", employee.getId()).eq("deleted", false));
        for (Train train : trains) {
            String trainImg = train.getTrainImg();
            if (!StringUtils.isEmpty(trainImg)) {
                if (trainImg.contains(",")) {
                    String[] split = trainImg.split(",");
                    train.setTrainImg1(split[0]);
                    train.setTrainImg2(split[1]);
                } else {
                    train.setTrainImg1(trainImg);
                }
            }
        }
        map.put("trains", trains);
        return "baseinfo/employee/edit";
    }

    @RequestMapping("/list")
    @ResponseBody
    public LayTableResponse listUI(Long departmentId, int page, int limit) {
        Wrapper<Employee> employeeWrapper = new EntityWrapper<Employee>().eq("orgId", currentUser.getOrgId()).eq("status", 1).eq("deleted", false).orderBy("createdTime", false);
        if (!StringUtils.isEmpty(departmentId) && departmentId != 0L) {
            employeeWrapper.eq("departmentId", departmentId);
        }

        Page<Employee> employeePage = employeeService.selectPage(new Page<Employee>(page, limit), employeeWrapper);
        return new LayTableResponse(employeePage.getRecords(), employeePage.getTotal());
    }

    @RequestMapping("/update")
    @ResponseBody
    public JsonResponse update(String data) {
        try {
            employeeService.updateEmployeeData(data, currentUser.getOrgId());
            return new JsonResponse(200, "成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResponse(0, "失败");
    }

    @RequestMapping("/save")
    @ResponseBody
    public JsonResponse save(String data) {
        try {
            employeeService.saveEmployeeData(data, currentUser.getOrgId());
            return new JsonResponse(200, "成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResponse(0, "失败");
    }

    /**
     * 删除
     *
     * @param
     * @return
     */
    @RequestMapping(path = "/delete")
    public String delete(@RequestParam("id") List<Long> ids) {
        employeeService.deleteBatchIds(ids);
        return "redirect:/employee";
    }

    /**
     * 离职
     *
     * @param
     * @return
     */
    @RequestMapping(path = "/leaveOffice")
    public String leaveOffice(Long id) {
        employeeService.leaveOffice(id);
        return "redirect:/employee";
    }

    /**
     * 到资质荣誉添加页面
     *
     * @return
     */
    @RequestMapping("/cert/save")
    @ResponseBody
    public JsonResponse save(EmployeeCertificate cert) {
        cert.setOrgId(currentUser.getOrgId());
        employeeCertificateService.insert(cert);
        return JsonResponse.success(cert);
    }

    @RequestMapping("/cert/delete")
    public String delete(Long id, Long employeeId) {
        employeeCertificateService.delete(new EntityWrapper<EmployeeCertificate>().eq("orgId", currentUser.getOrgId()).eq("id", id));
        return "redirect:/employee/edit?id=" + employeeId;
    }

    /**
     * 从业人员导出为excel
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping("/export/excel")
    public void exportExcel(HttpServletResponse response) {
        //查询所有的从业人员记录
        List<Employee> employees = employeeService.selectList(new EntityWrapper<Employee>().eq("orgId", currentUser.getOrgId()));
        //生成Excel,并存储临时文件
        // 创建一个HSSFWorkbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("从业人员");

        // 表头
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式

        //声明列对象
        HSSFCell cell = null;

        //创建标题
        String[] title = {"部门", "姓名", "身份证", "职位", "持证等级", "是否培训", "是否全职", "是否在职"};
        for (int i = 0; i < title.length; i++) {
            row.setHeightInPoints(20);
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
            sheet.setColumnWidth(i, 21 * 256);
        }

        //创建内容
        for (int i = 0; i < employees.size(); i++) {
            row = sheet.createRow(i + 1);
            row.setHeightInPoints(20);
            Employee employee = employees.get(i);
            row.createCell(0).setCellValue(employee.getDepartmentName());
            row.createCell(1).setCellValue(employee.getName());
            row.createCell(2).setCellValue(employee.getIdNo());
            row.createCell(3).setCellValue(employee.getPostName());
            if (employee.getGrade() == null) {
                employee.setGrade(0);
            }
            switch (employee.getGrade()) {
                case 1:
                    row.createCell(4).setCellValue("初级");
                    break;
                case 2:
                    row.createCell(4).setCellValue("中级");
                    break;
                case 3:
                    row.createCell(4).setCellValue("高级");
                    break;
                default:
                    row.createCell(4).setCellValue("未定级");
                    break;
            }
            if (employee.getTrainee() == null) {
                row.createCell(5).setCellValue("无需培训");
            } else {
                if (employee.getTrainee()) {
                    row.createCell(5).setCellValue("培训");
                } else {
                    row.createCell(5).setCellValue("未培训");
                }
            }

            if (employee.getFullTime()) {
                row.createCell(6).setCellValue("全职");
            } else {
                row.createCell(6).setCellValue("非全职");
            }

            if (employee.getStatus() == 1) {
                row.createCell(7).setCellValue("在职");
            } else if (employee.getStatus() == 2) {
                row.createCell(7).setCellValue("离职");
            }

        }

        //下载
        response.setCharacterEncoding("UTF-8");
        try (ServletOutputStream out = response.getOutputStream();) {
            response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("从业人员-" + TimeUtil.format(new Date(), "yyyyMMddHHmmss") + ".xls", "UTF-8"));
            wb.write(out);
        } catch (IOException e) {
            //TODO 下载失败日志记录
        } finally {
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查看从页人员信息
     *
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/message")
    public String message(Long id, ModelMap map) {
        Employee employee = employeeService.selectById(id);
        map.put("employee", employee);
        List<EmployeeCertificate> employeeCertificateList = employeeCertificateService.selectList(new EntityWrapper<EmployeeCertificate>().eq("employeeId", employee.getId()));
        map.put("employeeCertificateList", employeeCertificateList);
        return "baseinfo/employee/employeesMessage";
    }


    /**
     * 将从业人员的详情导出为PDF
     *
     * @param id
     * @param response
     * @throws Exception
     */
    @RequestMapping("/export/pdf")
    public void exportPdf(Long id, HttpServletResponse response) {
        //根据评估记录Id查询出从业人员信息
        Employee employee = employeeService.selectById(id);
        if (employee != null) {
            //生成PDF
            Map<String, Object> model = null;
            try {
                model = ObjectTransverter.objectToMap(employee);
            } catch (Exception e) {
                LOG.debug("数据转换失败: {}", e);
            }
            PDFGenerator gen = new PDFGenerator("templates/baseinfo/employee/pdftemplate/", ".html");

            File file = fs.getFile(employee.getAvatar());
            if (null != file) {
                assert model != null;
                model.put("avatar", "file:/" + FileUtil.separatorConvert(file.getAbsolutePath()));
            }
            //根据从业员信息查询 从业人员的资质证书
            List<EmployeeCertificate> employeeCertificateList = employeeCertificateService.selectList(new EntityWrapper<EmployeeCertificate>().eq("employeeId", employee.getId()));
            //创建一个集合存储从业人员的资质证书
//            ArrayList<String> path = new ArrayList<>();
            if (employeeCertificateList != null && employeeCertificateList.size() > 0) {
                for (EmployeeCertificate employeeCertificate : employeeCertificateList) {
                    File files = fs.getFile(employeeCertificate.getPath());
                    if (null != files) {
                        employeeCertificate.setPath("file:/" + FileUtil.separatorConvert(files.getAbsolutePath()));
                    }
                }
            }
            assert model != null;
            if (employeeCertificateList.size() < 1) {
                EmployeeCertificate employeeCertificate = new EmployeeCertificate();
                employeeCertificate.setPath("");
                employeeCertificateList.add(employeeCertificate);
            }
            model.put("employeeCertificateList", employeeCertificateList);


            //下载
            response.setCharacterEncoding("UTF-8");
            try (ServletOutputStream out = response.getOutputStream();) {
                response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("从业人员-" + employee.getPostName() + "-" + employee.getName() + ".pdf", "UTF-8"));
                gen.generate("employeesMessageTemplate", model, out);
            } catch (Exception e) {
                //TODO 下载失败日志记录
            }
        }
    }


}


